package cn.tansanqinger.controller.chatroom;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.tansanqinger.pojo.Filemessage;
import cn.tansanqinger.pojo.Filename;
import cn.tansanqinger.pojo.User;
import cn.tansanqinger.service.chatroom.IFriendlistService;
import cn.tansanqinger.service.file.impl.FileDisposeServiceImpl;
import cn.tansanqinger.service.hymenu.IHyMenuServer;
import cn.tansanqinger.util.DateUtil;
import cn.tansanqinger.util.PageData;
import cn.tansanqinger.util.Tools;

@RequestMapping("/exchange")
@Controller
public class FileController {
	
	@Autowired
	private IHyMenuServer hyMenuServer;
	@Autowired
	private IFriendlistService fservice;
	@Autowired
	private FileDisposeServiceImpl dservice;
	
	@RequestMapping("/file")
	public ModelAndView file(ModelAndView mv, HttpServletRequest request) {
		mv = hyMenuServer.selectHyMenuAll(mv);
		mv.addObject("user", request.getSession().getAttribute("user"));
		mv.addObject("fileNamees", dservice.selectFilenameAll(request));
		mv.setViewName("chatroom/file");
		return mv;
	}
	
	@RequestMapping("/file2")
	@ResponseBody
	public PageData file2(HttpServletRequest request) {
		PageData pd = new PageData();
		pd.put("user", request.getSession().getAttribute("user"));
		pd.put("fileNamees", dservice.selectFilenameAll(request));
		return pd;
	}
	
	/**
	 * 查询文件夹信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectFilenameAll")
	@ResponseBody
	public List<Filename> selectFilenameAll(HttpServletRequest request){
		return dservice.selectFilenameAll(request);
	}
	
	/**
	 * 查询文件信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/selectFileMessageAll")
	@ResponseBody
	public List<Filemessage> selectFileMessageAll(HttpServletRequest request){
		return dservice.selectFileMessageAll(request);
	}

	/**
	 * 删除文件夹
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteFileName")
	@ResponseBody
	public PageData deleteFileName(HttpServletRequest request) {
		return dservice.deleteFileName(request);
	}
	
	/**
	 * 删除文件
	 * @param request
	 * @return
	 */
	@RequestMapping("/deleteFileMessage")
	@ResponseBody
	public PageData deleteFileMessage(HttpServletRequest request) {
		return dservice.deleteFileMessage(request);
	}
	
	/**
	 * 修改文件夹名称
	 * @param request
	 * @return
	 */
	@RequestMapping("/modificationFileName")
	@ResponseBody
	public PageData modificationFileName(HttpServletRequest request) {
		return dservice.modificationFileName(request);
	}
	
	/**
	 * 修改文件名
	 * @param request
	 * @return
	 */
	@RequestMapping("/modificationFileMessage")
	@ResponseBody
	public PageData modificationFileMessage(HttpServletRequest request) {
		return dservice.modificationFileMessage(request);
	}
	
	/**
	 * 修改文件到不同文件夹中
	 * @param request
	 * @return
	 */
	@RequestMapping("/modificationFileToNewFile")
	@ResponseBody
	public PageData modificationFileToNewFile(HttpServletRequest request) {
		return dservice.modificationFileToNewFile(request);
	}
	
	/**
	 * 添加文件夹
	 * @param request
	 * @return
	 */
	@RequestMapping("/newFile")
	@ResponseBody
	public PageData newFile(HttpServletRequest request) {
		return dservice.addFileName(request);
	}
	
	/**
	 * 上传文件
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/uploadfile")
	@ResponseBody
    public String uploadfile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		JSONObject result = new JSONObject();
		try {
			if (file.isEmpty()) {
				result.put("code", "-1");
				result.put("msg", "请选择文件");
	        } else {
	        	Filemessage filemessage = new Filemessage();
	    		User user = (User) request.getSession().getAttribute("user");
	    		filemessage.setFdate(DateUtil.getTime());
	    		filemessage.setFid(Integer.parseInt(Tools.isEmpty(request.getParameter("fid"))));
	    		filemessage.setFname(file.getOriginalFilename());
	        	String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
	    		filemessage.setFsize(file.getSize());
	    		filemessage.setFtime(System.currentTimeMillis()/1000);
	    		filemessage.setUid(user.getId());
	    		filemessage.setFurl(fileName);
		        File upload = new File(System.getProperty("user.dir"),"/src/main/resources/resources/user/file/"+fileName);
		        if(!upload.exists()) upload.mkdirs();
		        file.transferTo(upload);
		        int fuid = dservice.addFileMessage(filemessage);
		        if(fuid>0) {
		        	result.put("msg", "文件上传成功");
			        result.put("code", "0");
			        result.put("fname", filemessage.getFname());
			        result.put("date", filemessage.getFdate());
			        result.put("fsize", filemessage.getFsize());
			        result.put("fuid", fuid);
		        } else {
		        	result.put("msg", "文件上传失败");
			        result.put("code", "0");
				}
	        }
	        return result.toString();
		} catch (Exception e) {}
        return null;
    }
	
	@RequestMapping("/downloadFile")
	@ResponseBody
	public byte[] downloadFile(HttpServletRequest request) {
		byte[] bytes = null ;
		try {
			Filemessage filemessage = dservice.selectFilemessageOne(Integer.parseInt(Tools.isEmpty(request.getParameter("id"))));
			File file = new File(System.getProperty("user.dir"),"/src/main/resources/resources/user/file/"+filemessage.getFurl());
			if (!file.exists()) {
				System.err.println("文件错误");
			}
			@SuppressWarnings("resource")
			FileInputStream inputStream = new FileInputStream(file);
//			int length = inputStream.available();
			bytes = new byte[inputStream.available()];
	        inputStream.read(bytes);
		} catch (Exception e) {}
		return bytes;
	}
	
}
